package com.nidu.demo.tenant.executor.query;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.tenant.convertor.TenantConvertor;
import com.nidu.demo.tenant.convertor.TenantCriteriaConvertor;
import com.nidu.demo.tenant.dto.TenantCO;
import com.nidu.demo.tenant.dto.TenantListQry;
import com.nidu.demo.tenant.gateway.TenantGateway;
import com.nidu.demo.tenant.model.Tenant;
import com.nidu.demo.tenant.model.TenantCriteria;
import com.nidu.demo.user.gateway.UserGateway;
import com.nidu.demo.user.model.User;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 租户列表查询执行器
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class TenantListQryExe {

    private final TenantGateway gateway;

    private final TenantConvertor convertor;

    private final TenantCriteriaConvertor criteriaConvertor;

    private final UserGateway userGateway;

    public MultiResponse<TenantCO> execute(TenantListQry qry) {
        TenantCriteria criteria = criteriaConvertor.toDataObject(qry);
        List<Tenant> tenants = gateway.listByCondition(criteria);
        if(CollUtil.isEmpty(tenants)){
            throw new BizException(ErrorCodeConstants.TENANT_NOT_FOUND.getCode(), ErrorCodeConstants.TENANT_NOT_FOUND.getMessage());
        }

        List<TenantCO> tenantCOS = convertor.toClientObjects(tenants);

        // 查询管理员名称
        Set<Long> userIds = tenantCOS.stream().map(TenantCO::getAdminId).collect(Collectors.toSet());
        if(!CollUtil.isEmpty(userIds)){
            List<User> users = userGateway.getByIds(userIds);
            Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, Function.identity()));
            tenantCOS.forEach(item -> {
                item.setAdminName(userMap.get(item.getId()).getNickname());
                item.setAdminMobile(userMap.get(item.getId()).getMobile());
            });
        }
        return MultiResponse.of(tenantCOS);
    }

}